package top.bbman.boot.ali.component;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.bbman.boot.ali.config.AliYunConfig;
import top.bbman.boot.ali.model.PeaStsTokenInfo;
import top.bbman.boot.ali.model.PeaOssPolicy;
import top.bbman.boot.logger.LogConstant;
import top.bbman.boot.repository.constant.PeaBeanName;
import top.bbman.boot.repository.constant.PeaConfigName;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * 阿里云的 OSS
 *
 * @author 祥霸
 * @version 1.0
 */
@Component(PeaBeanName.Ali.OSS)
public class PeaOssComponent {

    @Resource(name = PeaConfigName.Ali.ALI_YUN)
    private AliYunConfig aliYunConfig;

    /**
     * @param policy 权限策略
     * @param roleArn https://ram.console.aliyun.com/roles
     * @param roleName 自定义
     * @return
     */
    public PeaStsTokenInfo ossStsToken(PeaOssPolicy policy, String roleArn, String roleName) {

        if(Objects.isNull(policy)) {
            return null;
        }

        //构建一个阿里云客户端，用于发起请求。
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile(this.aliYunConfig.getRegionId(), this.aliYunConfig.getAccessKeyId(), this.aliYunConfig.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。关于参数含义和设置方法，请参见《API参考》。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleName);

        request.setPolicy(JSON.toJSONString(policy));
        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            PeaStsTokenInfo tokenInfo = new PeaStsTokenInfo();
            tokenInfo.setAccessKeyId(response.getCredentials().getAccessKeyId());
            tokenInfo.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
            tokenInfo.setSecurityToken(response.getCredentials().getSecurityToken());
            tokenInfo.setExpiration(this.utcToCn(response.getCredentials().getExpiration()).getTime());

            return tokenInfo;
        } catch (ServerException e) {
            LogConstant.bbManAli.error("ServerException ", e);
        } catch (ClientException e) {
            LogConstant.bbManAli.error("ErrCode: {}", e.getErrCode());
            LogConstant.bbManAli.error("ErrMsg: {}", e.getErrMsg());
            LogConstant.bbManAli.error("RequestId: {}", e.getRequestId());
        }

        return null;
    }

    /**
     * @param dateTime 2019-05-21T08:44:00Z
     */
    private Date utcToCn(String dateTime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            Date date = sdf.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+8);
            return calendar.getTime();
        }catch (Exception e) {
            LogConstant.bbManAli.error("utcToCnError", e);
        }
        return new Date();
    }
}
